package com.example.hydropowermanage.service.lmpl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hydropowermanage.mapper.UtilityUsageMapper;
import com.example.hydropowermanage.pojo.UtilityUsage;
import com.example.hydropowermanage.service.UtilityUsageService;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UtilityUsageServiceImpl extends ServiceImpl<UtilityUsageMapper, UtilityUsage> implements UtilityUsageService {

    //查找某个用户的所有水电信息
    public List<UtilityUsage> findAllByUserId(int userId) {
        QueryWrapper<UtilityUsage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userID", userId);
        return this.list(queryWrapper);
    }
    // 删除某个用户的所有水电信息
    //根据userID,将所有的水电信息删除
    public void removeAllByUserId(int userId) {
        QueryWrapper<UtilityUsage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userID", userId);
        this.remove(queryWrapper);
    }

    // 修改某个用户的水,电单价
    public void updatePricesByUserId(int userId, double newWaterPrice, double newElectricityPrice) {
        UpdateWrapper<UtilityUsage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userID", userId)
                .set("perWaterPrice", newWaterPrice)
                .set("perElectricityPrice", newElectricityPrice);

        this.update(updateWrapper);
    }
    //检查id是否唯一
    public boolean checkIdUnique(int recordId) {
        QueryWrapper<UtilityUsage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", recordId);
        return this.count(queryWrapper) == 0;
    }

    public void addUtilityUsage(UtilityUsage utilityUsage) {
        // 添加新记录
        this.save(utilityUsage);
    }
    public void updateUtilityUsage(UtilityUsage utilityUsage) {
        // 更新记录
        this.updateById(utilityUsage);
    }

    public UtilityUsage findById(int recordId) {
        // 根据ID查找记录
        return this.getById(recordId);
    }
    //根据userID,usageMonth查找记录
    public List<UtilityUsage> selectListByMonth(int userId, Date usageMonth) {
        QueryWrapper<UtilityUsage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userID", userId);

        // 获取 usageMonth 字段的年份和月份
        Calendar cal = Calendar.getInstance();
        cal.setTime(usageMonth);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1; // Calendar.MONTH 是从 0 开始的

        String yearMonthCondition = String.format("YEAR(usageMonth) = %d AND MONTH(usageMonth) = %d", year, month);
        queryWrapper.apply(yearMonthCondition);

        return this.list(queryWrapper);
    }

}
